<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Labor;
use App\Models\LaborTemplate;
use Illuminate\Support\Facades\Log;

class LaborTemplateService
{
    public function get($type){
        $sql = Labor::with('application')->where('type',$type)->with('project')->with('user');
        return $sql;
    }

    public function insert($input){
        try {
            $data = new LaborTemplate();
            $data->labor_contract_id = $input['labor_contract_id'];
            $data->labor_id = $input['labor_id'] ?? 0;
            $data->project_id = $input['project_id'];
            $data->user_id = $input['user_id'];
            $data->type = $input['type'];
            $data->content = $input['content'];
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        try {
            $data = LaborTemplate::where('type',$input['type'])->where('labor_contract_id',$input['labor_contract_id'])->first();
            if(!$data){
                $data = new LaborTemplate();
                $data->labor_contract_id = $input['labor_contract_id'];
            }
            $data->labor_contract_id = $input['labor_contract_id'];
            $data->labor_id = $input['labor_id'] ?? 0;
            $data->project_id = $input['project_id'];
            $data->user_id = $input['user_id'];
            $data->type = $input['type'];
            $data->content = $input['content'];
            $data->save();
            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}